import React, { useEffect, useRef, useState } from 'react';
import { Card, Input } from 'antd';  // 添加 Input 导入
import cytoscape from 'cytoscape';
import { fetchGraphData } from '@/services/auth';
import styles from './index.module.css';

const { Search } = Input;  // 添加这行

const GraphPage: React.FC = () => {
  const cyRef = useRef<HTMLDivElement | null>(null);
  const [loading, setLoading] = useState(false);
  const [cy, setCy] = useState<any>(null);

  // 将颜色数组移到组件顶部
  const colors = [
    '#FF6B6B', // 红色
    '#4ECDC4', // 青色
    '#FFD93D', // 黄色
    '#6C5CE7', // 紫色
    '#A8E6CF', // 薄荷绿
    '#FF8C94', // 粉色
    '#45B7D1', // 蓝色
    '#96CEB4', // 淡绿
    '#FFEEAD', // 米黄
    '#D4A5A5'  // 玫瑰粉
  ];

  const handleSearch = async (value: string) => {
    if (!value.trim()) {
      initGraph();
      return;
    }

    setLoading(true);
    try {
      // 使用 URLSearchParams 构建查询参数
      const params = new URLSearchParams({
        keyword: value.trim()
      }).toString();
      
      const data = await fetchGraphData(`?${params}`);
      console.log('搜索参数:', params);
      console.log('搜索返回的数据:', data);

      if (!data || !data.nodes || !data.relationships) {
        console.error('数据格式错误:', data);
        return;
      }
      
      // 更新图谱数据
      if (cy) {
        // 先移除所有现有元素
        cy.elements().remove();

        // 只添加搜索结果相关的节点和边
        const elements = {
          nodes: data.nodes.map((node: any) => ({
            data: { 
              id: node.id, 
              label: node.properties.name,
              color: colors[Math.floor(Math.random() * colors.length)]
            },
            classes: node.labels[0].toLowerCase()
          })),
          edges: data.relationships.map((rel: any) => ({
            data: {
              id: rel.id,
              source: rel.startNode,
              target: rel.endNode,
              label: rel.type
            }
          }))
        };

        // 一次性添加所有元素
        cy.add(elements);

        // 重新运行布局
        cy.layout({
          name: 'cose',
          padding: 80,
          animate: false,
          nodeDimensionsIncludeLabels: true,
          randomize: false,
          componentSpacing: 200,
          nodeRepulsion: 10000,
          edgeElasticity: 200,
          gravity: 0.3,
          idealEdgeLength: 180,
          numIter: 1000
        }).run();

        // 调整视图以适应新的元素
        setTimeout(() => {
          cy.fit();
          cy.center();
        }, 500);
      }
    } catch (error) {
      console.error('搜索图谱数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const initGraph = async () => {
      setLoading(true);
      try {
        const data = await fetchGraphData();
        console.log('获取到的图谱数据:', data);

        if (!data || !data.nodes || !data.relationships) {
          console.error('数据格式错误:', data);
          return;
        }

        if (cyRef.current) {
          // 确保容器尺寸
          cyRef.current.style.width = '100%';
          cyRef.current.style.height = '100%';

          const instance = cytoscape({
            container: cyRef.current,
            elements: {
              nodes: data.nodes.map((node: any) => ({
                data: { 
                  id: node.id, 
                  label: node.properties.name,
                  color: colors[Math.floor(Math.random() * colors.length)]
                },
                classes: node.labels[0].toLowerCase()
              })),
              edges: data.relationships.map((rel: any) => ({
                data: {
                  id: rel.id,
                  source: rel.startNode,
                  target: rel.endNode,
                  label: rel.type
                }
              }))
            },
            style: [
              {
                selector: 'node',
                style: {
                  'label': 'data(label)',
                  'text-valign': 'bottom',
                  'text-halign': 'center',
                  'width': '45px',
                  'height': '45px',
                  'font-size': '14px',
                  'text-outline-width': 2,
                  'text-outline-color': '#FFFFFF',
                  'text-outline-opacity': 0.9,
                  'color': '#333333',
                  'font-weight': '600',
                  'border-width': '2px',
                  'border-opacity': 1,
                  'background-opacity': 1,
                  'background-color': 'data(color)',  // 使用随机颜色
                  'border-color': 'data(color)',      // 边框颜色与节点颜色一致
                  'shadow-blur': '10px',
                  'shadow-color': 'rgba(0, 0, 0, 0.3)',
                  'shadow-opacity': 0.5,
                  'shadow-offset-x': '0px',
                  'shadow-offset-y': '4px',
                  'text-margin-y': '5px'
                }
              },
              {
                selector: 'node.person',
                style: {
                  'background-color': '#FF6B6B',  // 鲜艳的红色
                  'background-gradient-stop-colors': '#FF6B6B #FF8787',
                  'border-color': '#FF5252'
                }
              },
              {
                selector: 'node.theory',
                style: {
                  'background-color': '#4ECDC4',  // 清新的青色
                  'background-gradient-stop-colors': '#4ECDC4 #7BE0D8',
                  'border-color': '#45B7AF'
                }
              },
              {
                selector: 'node.theory',
                style: {
                  'background-color': '#F28E2B',
                  'shape': 'round-rectangle',
                  'border-color': '#D97A1B',
                  'background-gradient-stop-colors': '#F28E2B #FFB366',
                  'background-gradient-direction': 'to-bottom-right'
                }
              },
              {
                selector: 'edge',
                style: {
                  'width': 2,
                  'line-color': '#6E7B8B',
                  'target-arrow-color': '#6E7B8B',
                  'target-arrow-shape': 'triangle',
                  'curve-style': 'bezier',
                  'label': 'data(label)',
                  'font-size': '12px',
                  'color': '#666666',
                  'text-rotation': 'autorotate',
                  'text-margin-y': -5,
                  'text-background-color': '#FFFFFF',
                  'text-background-opacity': 0.9,
                  'text-background-padding': 4,
                  'text-background-shape': 'round-rectangle'
                }
              },
              {
                selector: 'edge:selected',
                style: {
                  'line-color': '#FFD700',
                  'target-arrow-color': '#FFD700',
                  'width': 3,
                  'text-background-color': '#FFF8DC'
                }
              },
              {
                selector: 'node:selected',
                style: {
                  'border-width': '3px',
                  'border-color': '#FFD700',
                  'shadow-blur': '15px',
                  'shadow-color': 'rgba(255, 215, 0, 0.5)',
                  'shadow-opacity': 0.7
                }
              }
            ],
            layout: {
              name: 'cose',
              padding: 80,
              animate: false,
              nodeDimensionsIncludeLabels: true,
              randomize: false,
              componentSpacing: 200,
              nodeRepulsion: 10000,
              edgeElasticity: 200,
              gravity: 0.3,
              idealEdgeLength: 180,
              numIter: 1000,
              initialTemp: 30,
              coolingFactor: 0.95
            },
            minZoom: 0.3,
            maxZoom: 2.5,
            wheelSensitivity: 0.15,
            userZoomingEnabled: true,
            userPanningEnabled: true,
            boxSelectionEnabled: true
          });

          setCy(instance);

          // 等待布局完成后再进行缩放和居中
          setTimeout(() => {
            instance.fit();
            instance.center();
          }, 100);
        }
      } catch (error) {
        console.error('加载图谱数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    initGraph();

    return () => {
      if (cy) {
        cy.destroy();
      }
    };
  }, []);

  return (
    <div className={styles.container}>
      <Card variant="borderless" style={{ height: '90vh', position: 'relative' }}>
        <Search
          placeholder="搜索节点..."
          onSearch={handleSearch}
          style={{
            position: 'absolute',
            top: 20,
            right: 20,
            width: 300,
            zIndex: 1000,
            boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
            borderRadius: '6px'
          }}
          allowClear
        />
        <div ref={cyRef} style={{ 
          width: '100%', 
          height: '100%',
          minHeight: '600px',
          position: 'relative'
        }} />
      </Card>
    </div>
  );
};

export default GraphPage;